//
//  SearchViewController.m
//  ThePrivateKitchen
//
//  Created by lirui on 16/1/26.
//  Copyright © 2016年 www.lanou3g.com蓝鸥科技. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchModel.h"

#import "ShikeViewController.h"
#import "MyPCH.pch"
#import "SearchTableViewCell.h"
@interface SearchViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>
@property(nonatomic ,retain)UISearchBar *searchBar;
@property(nonatomic,retain)UITableView *tableView;
@property(nonatomic,retain)NSMutableArray *dataArr;
@property(nonatomic,retain)SearchModel *s_model;
//@property(nonatomic, retain)UISearchController *searchController;
@property(nonatomic,retain)NSString *searchString;
@end

@implementation SearchViewController
- (void)dealloc
{
    [_searchBar release];
    [_tableView release];
    [_dataArr release];
    [_s_model release];
    [_searchString release];
    [super dealloc];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
    self.view.backgroundColor = [ UIColor whiteColor];
    
    [self createNavigationBar];
    //[self prepareData];
    
    [self creatView];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"left@3x"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftAction:)];
    
}
-(void)leftAction:(UIBarButtonItem *)left
{
    [self.navigationController popViewControllerAnimated:YES];
}


 //搜索的基本设置
- (void)createNavigationBar
    {
        
        // 创建titleView
        UIButton *titleView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 280 * WIDTH , 30 * HEIGHT)];
        self.navigationItem.titleView = titleView;
        self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 280 * WIDTH, 30 *HEIGHT)];
        self.searchBar.delegate = self;
        [self.searchBar setBarStyle:UIBarStyleDefault];
        [self.searchBar setKeyboardType:UIKeyboardTypeDefault];
        self.searchBar.layer.masksToBounds = YES;
        self.searchBar.layer.cornerRadius = 10;
        
        // 成为第一响应者
        [self.searchBar becomeFirstResponder];
        self.searchBar.placeholder = @"输入菜名或食材搜索";
        [titleView addSubview:self.searchBar];
        [_searchBar release];
    }
#pragma mark - 搜索方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
    {
        // 搜索框失去第一响应者
        [self.searchBar resignFirstResponder];
        // 准备数据
        [self prepareData];
    }
    
#pragma mark - 准备数据
- (void)prepareData
    {
        
        NSString* str = [self.searchBar text];
        
        if ([str containsString:@" "]|| _dataArr.count == 0) {
      
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"未搜索到结果" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [self.navigationController popToRootViewControllerAnimated:YES];
            }];
              UIAlertAction *cancel = [ UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                  
              }];
           
            // 给alert添加操作
            
            [alert addAction: cancel];
            [alert addAction:okAction];
            // 模态显示
            [self presentViewController:alert animated:YES completion:nil];

        }
        else
        {
        NSString *urlStr = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:str]];
        
        

        NSString *str1 = [NSString stringWithFormat:@"http://api.izhangchu.com/?keyword=%@&methodName=SearchDishes&page=1&size=10&version=4.01",urlStr];
        [LRAFNetwork postUrlString:str1 body:nil response:JSON bodyStyle:RequestJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id responseObject) {
            NSArray *arr = responseObject[@"data"][@"data"];
            self.dataArr = [SearchModel modelHanderWithArray:arr];
            if (self.tableView == nil) {
                // 如果tableView不存在创建tableView
                [self creatView];
            }else{
                // 如果tableView已创建 刷新数据
                [self.tableView reloadData];
            }

        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
        }];
        }
    }
#pragma mark - 创建tableView
//创建tableview
-(void)creatView
{
    self.tableView = [[ UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH *375, HEIGHT *667) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView .delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[SearchTableViewCell class] forCellReuseIdentifier:@"cell"];
    [_tableView release];
    [self.view addSubview:_tableView];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.key = self.searchBar.text;
    cell.dishModel = self.dataArr[indexPath.row];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    return cell;
    
}

#pragma mark - 行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150 *HEIGHT;
}










#pragma mark - 点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SancanVIdeoViewController *svideo =[[ SancanVIdeoViewController alloc] init];
    SearchModel *m = _dataArr[indexPath.row];
    svideo.str = m.dish_id ;
    NSLog(@"%@ %@",svideo.str,m.dish_id);
    [self.navigationController pushViewController:svideo animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
